package 重温_Java并发基础.Synchronized案例;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;

/**
 * @Author idea
 * @Date created in 9:19 下午 2020/8/17
 */
public class IncreaseDemo {

    private static int money = 0;

    private static final Object monitor = new Object();

    public static void increaseMoney(int n) {
        money += n;
    }



    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        CountDownLatch totalEnd = new CountDownLatch(2);
        Thread t1 = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                synchronized (monitor) {
                    countDownLatch.await();
                    for (int i = 0; i < 1000; i++) {
                        increaseMoney(1);
                    }
                    totalEnd.countDown();
                }
            }
        });


        Thread t2 = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                synchronized (monitor) {
                    countDownLatch.await();
                    for (int i = 0; i < 1000; i++) {
                        increaseMoney(2);
                    }
                    totalEnd.countDown();
                }
            }
        });

        t1.start();
        t2.start();
        countDownLatch.countDown();

        totalEnd.await();
        System.out.println("总数=====" + money);
    }
}
